package com.tanbaby.ProductsManagement;

import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.ArrayList;


@RestController
@RequestMapping("/products")
public class ProductController {

    private List<Product> products = new ArrayList<>();

    @GetMapping
    public List<Product> getAllProducts() {
        return products;
    }

    @GetMapping("/{id}")
    public Product getProductById(@PathVariable Long id) {
        //get Product
        for (Product product : products) {
            if (product.getId().equals(id)) {
                return product;
            }
        }
        return null;
    }

    @PostMapping
    public Product addProduct(@RequestBody Product product) {
        // add Product
        product.setId(System.currentTimeMillis()); // 使用当前时间作为 ID
        products.add(product);
        return product;
    }

    @PutMapping("/{id}")
    public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
        // update product
        for (Product p : products) {
            if (p.getId().equals(id)) {
                p.setName(product.getName());
                p.setPrice(product.getPrice());
                p.setSales(product.getSales());
                return p;
            }
        }
        return null;
    }

    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable Long id) {
        // delete product
        products.removeIf(product -> product.getId().equals(id));
    }
}

